from cStringIO import StringIO
import sys

class Reader:
    def __init__(self):
        pass
    
    def read(self, file):
        raise NotImplementedError()
    
    def read_file(self, filename):
        file = open(filename)
        result = self.read(file)
        file.close()
        return result
            
    def parse(self, string):
        file = StringIO(string)
        result = self.read(file)
        file.close()
        return result

class NamedReader(Reader):
    def read_file(self, filename):
        result = Reader.read_file(self, filename)
        try:
            name = result.name
        except:
            result.name = os.path.basename(filename)
        return result

class Writer:
    def write(self, file, v):
        raise NotImplementedError(type(self))
    
    def write_file(self, filename, v):
        file = open(filename, "w")
        result = self.write(file, v)
        file.close()
        return result
        
    def to_string(self, v):
        file = StringIO()
        result = self.write(file, v)
        file.close()
        return result
        

import re
LINE_SPLITTER = re.compile(r"[\n|\r]+")
    
def print_title(title, output=sys.stdout, char='=', width=72, level = 1):
    tokens = [i.strip() for i in LINE_SPLITTER.split(title)]
    width = width - 8 * level
    for i in tokens:
        nspace = (width - len(i)) / 2 + level * 4 
        output.write(' ' * nspace + i + ' ' * nspace + '\n')
    output.write(' ' * (level * 4) + char*width + ' ' * (level * 4) + '\n')
    
def print_vertical_bar(output=sys.stdout, char='-', width=72, level = 0):
    width = width - 8 * level
    output.write(' ' * (level * 4) + char*width + ' ' * (level * 4) + '\n')

def print_block(content, output=sys.stdout, char='*', width=72, level=0):
    print_vertical_bar(output, char, width, level)
    tokens = [i.strip() for i in LINE_SPLITTER.split(content)]
    width = width - 8 * level
    
    output.write(' ' * (level*4) + char + ' ' * (width-level*8-2) + char + ' ' * (level*4) + "\n")
    for i in tokens:
        nspace1 = (width - len(i)) / 2 - 1
        nspace2 = width - len(i) - 2 - nspace1
        output.write(' ' * (level*4) + char + ' ' * nspace1 + i + ' ' * nspace2 + char +' ' * (level*4) + '\n')
    output.write(' ' * (level*4) + char + ' ' * (width-level*8-2) + char + ' ' * (level*4) + "\n")        
    print_vertical_bar(output, char, width, level)
